package com.gzj.environment.framework.service.impl;

import com.gzj.environment.framework.service.CacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * redis实现缓存过期时间
 */
@Service
public class RedisCacheService implements CacheService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 设置键值对，并更新过期时间
     *
     * @param key   键
     * @param value 值
     * @param ttl   过期时间，单位毫秒
     * @return
     */
    @Override
    public void setAndResetExpireTime(String key, Object value, long ttl) {
        ValueOperations operations = redisTemplate.opsForValue();
        operations.set(key, value, ttl, TimeUnit.MILLISECONDS);
    }

    /**
     * 设置键值对，不更新过期时间
     *
     * @param key   键
     * @param value 值
     * @return
     */
    @Override
    public void setNotResetExpireTime(String key, Object value) {
        ValueOperations operations = redisTemplate.opsForValue();
        long ttl = redisTemplate.getExpire(key, TimeUnit.MILLISECONDS);
        operations.set(key, value, ttl, TimeUnit.MILLISECONDS);
    }

    /**
     * 根据键获取值
     *
     * @param key 键
     * @return
     */
    @Override
    public Object get(String key) {
        ValueOperations operations = redisTemplate.opsForValue();
        return operations.get(key);
    }

    /**
     * 根据键移除指定的键值对
     *
     * @param key 键
     * @return
     */
    @Override
    public void remove(String key) {
        redisTemplate.delete(key);
    }
}
